<template>
  <div class="create-application-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>发起测试申请</span>
        </div>
      </template>
      
      <el-form ref="applicationForm" :model="applicationForm" :rules="applicationRules" class="application-form">
        <el-form-item prop="productId" label="产品名称" :label-width="formLabelWidth">
          <el-select
            v-model="applicationForm.productId"
            placeholder="请选择产品"
            style="width: 100%"
            @change="handleProductChange"
          >
            <el-option
              v-for="product in productList"
              :key="product.id"
              :label="product.productName"
              :value="product.id"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item prop="versionId" label="版本号" :label-width="formLabelWidth">
          <el-select
            v-model="applicationForm.versionId"
            placeholder="请选择版本"
            style="width: 100%"
            :disabled="!applicationForm.productId"
          >
            <el-option
              v-for="version in versionList"
              :key="version.id"
              :label="version.versionName"
              :value="version.id"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item prop="testType" label="测试类型" :label-width="formLabelWidth">
          <el-checkbox-group v-model="applicationForm.testType">
            <el-checkbox label="功能测试" border></el-checkbox>
            <el-checkbox label="性能测试" border></el-checkbox>
            <el-checkbox label="安全测试" border></el-checkbox>
            <el-checkbox label="回归测试" border></el-checkbox>
            <el-checkbox label="兼容性测试" border></el-checkbox>
            <el-checkbox label="其他测试" border></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item prop="description" label="申请说明" :label-width="formLabelWidth">
          <el-input
            v-model="applicationForm.description"
            type="textarea"
            placeholder="请详细描述测试需求、测试范围、测试重点等信息"
            :rows="5"
          ></el-input>
        </el-form-item>
        
        <el-form-item prop="expectCompletionTime" label="期望完成时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="applicationForm.expectCompletionTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item prop="testContact" label="测试联系人" :label-width="formLabelWidth">
          <el-input
            v-model="applicationForm.testContact"
            placeholder="请输入测试联系人姓名"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        
        <el-form-item prop="testContactPhone" label="联系电话" :label-width="formLabelWidth">
          <el-input
            v-model="applicationForm.testContactPhone"
            placeholder="请输入联系电话"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        
        <el-form-item prop="attachments" label="附件上传" :label-width="formLabelWidth">
          <el-upload
            action="/api/upload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :file-list="fileList"
            :auto-upload="false"
            ref="upload"
            :data="{ type: 'application' }"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传jpg/png/pdf/doc/docx格式文件，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交申请</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import router from '../../router'
import { ElMessage } from 'element-plus'

export default {
  name: 'CreateApplication',
  setup() {
    const applicationForm = ref({
      productId: '',
      versionId: '',
      testType: [],
      description: '',
      expectCompletionTime: '',
      testContact: '',
      testContactPhone: '',
      attachments: []
    })
    
    const applicationRules = ref({
      productId: [{ required: true, message: '请选择产品', trigger: 'blur' }],
      versionId: [{ required: true, message: '请选择版本', trigger: 'blur' }],
      testType: [
        { required: true, message: '请至少选择一种测试类型', trigger: 'change' },
        { type: 'array', min: 1, message: '请至少选择一种测试类型', trigger: 'change' }
      ],
      description: [{ required: true, message: '请输入申请说明', trigger: 'blur' }],
      expectCompletionTime: [{ required: true, message: '请选择期望完成时间', trigger: 'change' }],
      testContact: [{ required: true, message: '请输入测试联系人', trigger: 'blur' }],
      testContactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ]
    })
    
    const formLabelWidth = '120px'
    const productList = ref([])
    const versionList = ref([])
    const fileList = ref([])
    
    // 初始化数据
    onMounted(() => {
      fetchProductList()
    })
    
    // 获取产品列表
    const fetchProductList = async () => {
      try {
        // 尝试从后端API获取数据
        const response = await axios.get('/api/products')
        if (response.data.code === 200) {
          productList.value = response.data.data.list || []
        }
      } catch (error) {
        // 使用模拟数据，不显示错误日志以避免用户混淆
        productList.value = [
          { id: 1, productName: '测试系统A' },
          { id: 2, productName: '测试系统B' },
          { id: 3, productName: '测试系统C' }
        ]
      }
    }
    
    // 产品变更时获取版本列表
    const handleProductChange = async () => {
      if (!applicationForm.value.productId) {
        versionList.value = []
        applicationForm.value.versionId = ''
        return
      }
      
      try {
        const response = await axios.get(`/api/product/${applicationForm.value.productId}/versions`)
        if (response.data.code === 200) {
          versionList.value = response.data.data
        }
      } catch (error) {
        console.error('获取版本列表失败:', error)
        // 使用模拟数据
        versionList.value = [
          { id: 1, versionName: 'V1.0.0' },
          { id: 2, versionName: 'V1.0.1' },
          { id: 3, versionName: 'V1.0.2' }
        ]
      }
    }
    
    // 上传成功回调
    const handleUploadSuccess = (response, file, fileList) => {
      if (response.code === 200) {
        applicationForm.value.attachments.push({
          name: file.name,
          url: response.data.url,
          size: file.size
        })
        ElMessage.success('上传成功')
      } else {
        ElMessage.error(response.message || '上传失败')
      }
    }
    
    // 上传失败回调
    const handleUploadError = (error, file, fileList) => {
      ElMessage.error('上传失败，请检查网络或稍后重试')
    }
    
    // 提交申请
    const handleSubmit = async () => {
      try {
        // 先手动上传所有文件
        if (fileList.value.length > 0) {
          await uploadFiles()
        }
        
        // 提交表单数据
        const response = await axios.post('/api/application', applicationForm.value)
        
        if (response.data.code === 200) {
          ElMessage.success('测试申请提交成功，请等待审核')
          router.push('/dashboard/application/list')
        } else {
          ElMessage.error(response.data.message || '提交失败')
        }
      } catch (error) {
        console.error('提交测试申请失败:', error)
        ElMessage.error('提交失败，请检查网络或稍后重试')
      }
    }
    
    // 上传文件
    const uploadFiles = () => {
      return new Promise((resolve, reject) => {
        if (fileList.value.length > 0) {
          const uploadPromise = Promise.all(
            fileList.value.map(file => {
              return new Promise((resolve, reject) => {
                // 模拟文件上传
                setTimeout(() => {
                  applicationForm.value.attachments.push({
                    name: file.name,
                    url: `/uploads/${file.name}`,
                    size: file.size
                  })
                  resolve()
                }, 500)
              })
            })
          )
          
          uploadPromise.then(() => {
            resolve()
          }).catch(error => {
            reject(error)
          })
        } else {
          resolve()
        }
      })
    }
    
    // 取消
    const handleCancel = () => {
      router.push('/dashboard/application/list')
    }
    
    return {
      applicationForm,
      applicationRules,
      formLabelWidth,
      productList,
      versionList,
      fileList,
      handleProductChange,
      handleUploadSuccess,
      handleUploadError,
      handleSubmit,
      handleCancel
    }
  }
}
</script>

<style scoped>
.create-application-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.el-card {
  border-radius: 12px;
  overflow: hidden;
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.el-card:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
}

.application-form {
  padding: 20px 24px;
}

.application-form .el-form-item {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.application-form .el-form-item:hover {
  transform: translateX(5px);
}

.application-form .el-form-item__label {
  font-weight: 600;
  color: #303133;
}

.application-form .el-input,
.application-form .el-select,
.application-form .el-date-picker {
  width: 100%;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.application-form .el-input:hover,
.application-form .el-select:hover,
.application-form .el-date-picker:hover {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.application-form .el-input:focus,
.application-form .el-select:focus,
.application-form .el-date-picker:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.3);
}

.application-form .el-input__inner {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.application-form .el-textarea__inner {
  border-radius: 6px;
  resize: vertical;
  min-height: 100px;
}

.el-checkbox {
  margin-right: 20px;
  margin-bottom: 15px;
  transition: all 0.2s ease;
}

.el-checkbox:hover {
  transform: scale(1.05);
}

.el-checkbox.is-checked .el-checkbox__label {
  color: #667eea;
  font-weight: 500;
}

.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #667eea;
  border-color: #667eea;
}

.el-upload {
  margin-top: 10px;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

.el-upload:hover {
  border-color: #667eea;
  background: #f0f2ff;
}

.el-upload__tip {
  margin-top: 15px;
  color: #909399;
  font-size: 12px;
}

.application-form .el-button {
  margin-right: 10px;
  border-radius: 6px;
  transition: all 0.3s ease;
  padding: 8px 20px;
}

.application-form .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
}

.application-form .el-button--primary:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.application-form .el-button--default:hover {
  border-color: #667eea;
  color: #667eea;
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .create-application-container {
    padding: 10px;
  }
  
  .card-header {
    padding: 16px 20px;
  }
  
  .application-form {
    padding: 16px 20px;
  }
}

@media (max-width: 768px) {
  .card-header {
    text-align: center;
  }
  
  .application-form {
    padding: 12px 16px;
  }
  
  .application-form .el-form-item {
    margin-bottom: 15px;
  }
  
  .application-form .el-form-item__label {
    width: 100%;
    text-align: left;
    margin-bottom: 5px;
  }
  
  .application-form .el-form-item__content {
    width: 100%;
  }
  
  .el-checkbox {
    margin-right: 15px;
    margin-bottom: 10px;
  }
  
  .application-form .el-button {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
}
</style>